package com.neusoft.mid.msf.common.util;

import com.neusoft.mid.msf.common.vo.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: pangu
 * @description: 树形结构操作的工具类
 * @author: fengjd
 * @create: 2022-07-21 20:53
 **/
public class TreeUtil {

    /**
     * 两层循环实现建树
     * @param treeNodes
     * @param root
     * @return
     * @param <T>
     */
    public static <T extends TreeNode> List<T> build(List<T> treeNodes,Object root) {
        List<T> trees = new ArrayList<>();
        for (T treeNode : treeNodes) {
            if (root.equals(treeNode.getParentId())) {
                trees.add(treeNode);
            }

            for (T it : treeNodes) {
                if (it.getParentId() == treeNode.getId()) {
                   if (treeNode.getChildren() ==null){
                       treeNode.setChildren(new ArrayList<TreeNode>());
                   }
                   treeNode.add(it);
                }
            }

        }

        return trees;
    }


    /**
     * 递归查找子节点
     * @param treeNodes
     * @param root
     * @return
     * @param <T>
     */
    public static <T extends TreeNode> List<T> buildByRecursize(List<T> treeNodes,Object root) {
        ArrayList<T> trees = new ArrayList<>();
        for (T treeNode : treeNodes) {
            if (root.equals(treeNode.getParentId())) {
                trees.add( findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    public static <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
        for (T it : treeNodes) {
            if (treeNode.getId() == it.getParentId()) {
                if (treeNode.getChildren()==null) {
                    treeNode.setChildren(new ArrayList<TreeNode>());
                }
                treeNode.add( findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }
}
